package com.example.homework8.model;

import java.sql.*;

public class DBTest {
   public String RealName;
    String username;
    String password;


    public void getLoginInfo(String username,String password) {
        this.username=username;
        this.password=password;
    }

    public void userLogin() {
        String url = "jdbc:mysql:///library_management?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC";
        String DBuser = "root";
        String DBpassword = "ly970805";
        Connection conn=null;
        PreparedStatement per=null;
        ResultSet res=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, DBuser, DBpassword);
            System.out.println(conn);
            //开始搬运数据
            String sql = "select * from user where username = ? and password = ?";
            per = conn.prepareStatement(sql);
            per.setString(1, username);
            per.setString(2, password);
            res = per.executeQuery();
            while (res.next()) {
                RealName=res.getString("name");
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (res != null) {
                try {
                    res.close();
                    System.out.println("数据库连接已关闭。");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (per != null) {
                try {
                    per.close();
                    System.out.println("数据库连接已关闭。");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 5. 关闭连接 (见下文)
            if (conn != null) {
                try {
                    conn.close();
                    System.out.println("数据库连接已关闭。");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}